package com.lepu.app.main.activity;

import java.util.HashMap;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.app.utils.AppWebChromClient;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.SdLocal;
import com.app.utils.UmengEvent;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.BrowserLocaljsObject;
import com.core.lib.utils.BrowserLocaljsObject.BrowserLocaljsObjectDelegate;
import com.core.lib.utils.BrowserWebChromeClient.BrowserWebChromeDelegate;
import com.core.lib.utils.BrowserWebClient;
import com.core.lib.utils.BrowserWebClient.BrowserWebClientDelegate;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.CustomWebView;
import com.core.lib.widget.CustomWebView.WebViewScrollInterface;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

/*
 * 自定义浏览器
 */
public class AppBroswerActivity extends AppBroswerActivityBase implements
		OnTopbarNewLeftLayoutListener, BrowserWebClientDelegate, AsyncRequest, BrowserLocaljsObjectDelegate,
		WebViewScrollInterface {

	private static final String REQUEST_ARTICLE_SHARE = "request_article_share";

	private FrameLayout mVideoFullView;// 全屏时视频加载view
	private View mCustomVideoView;
	private WebChromeClient.CustomViewCallback mCustomViewCallback;
	private MyWebChromeClient mMyWebChromeClient;
	private boolean mFirstEnterWebView = false;

	private CustomWebView mWebView = null;
	private ProgressBar mProgressBar = null;
	private CustomTopBarNew mTopbar = null;

	private String mTopbarTitle = "";
	private String mLoadData = "";
	private String mLoadUrl = "";
	private boolean mNeedShare = false;
	private int mFromType = Const.AppBroswerType.TYPE_DEFAULT;
	private String mShareTitle = "";

	private String mCover = "";
	private String mDescription = "";

	private ImageView mShareImageView = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		mNeedDefaultUmeng = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_broswer_activity);

		init();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onResume() {
		mWebView.onResume();
		mWebView.resumeTimers();
		super.onResume();
		
		if(mFromType == Const.AppBroswerType.TYPE_MY_YOU_HUI_QUAN)
		{
			UmengHelper.onResume(this, UmengEvent.page_wode_youhuijuan);
		}else if(mFromType == Const.AppBroswerType.TYPE_YUAN_CHENG_HUI_ZHEN)
		{
			UmengHelper.onResume(this, UmengEvent.page_yuanchenghuizhen);
		}
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onPause() {
		mWebView.onPause();
		mWebView.pauseTimers();
		super.onPause();
		
		if(mFromType == Const.AppBroswerType.TYPE_MY_YOU_HUI_QUAN)
		{
			UmengHelper.onPause(this, UmengEvent.page_wode_youhuijuan);
		}else if(mFromType == Const.AppBroswerType.TYPE_YUAN_CHENG_HUI_ZHEN)
		{
			UmengHelper.onPause(this, UmengEvent.page_yuanchenghuizhen);
		}
	}

	@Override
	public void onDestroy() {
		mVideoFullView.removeAllViews();
		mWebView.loadUrl("about:blank");
		mWebView.stopLoading();
		mWebView.setWebChromeClient(null);
		mWebView.setWebViewClient(null);
		mWebView.destroy();
		mWebView = null;

		super.onDestroy();
	}

	public void onBackPressed() {
		closePage();
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void init() {
		mTopbar = (CustomTopBarNew) findViewById(R.id.broswerTopBar);
		mTopbar.setonTopbarNewLeftLayoutListener(this);
		mTopbar.setTopbarLeftLayout(R.drawable.app_icon_close, 0, 0);

		mProgressBar = (ProgressBar) findViewById(R.id.topProgressBar);
		mWebView = (CustomWebView) findViewById(R.id.webView);
		mWebView.setWebViewClient(new BrowserWebClient(this, this, mWebView));

		mVideoFullView = (FrameLayout) findViewById(R.id.videoFullView);
		mMyWebChromeClient = new MyWebChromeClient();
		mWebView.setWebChromeClient(mMyWebChromeClient);
		mWebView.setOnCustomScroolChangeListener(this);

		// test video
		BrowserLocaljsObject jsObj = new BrowserLocaljsObject(this);
		mWebView.addJavascriptInterface(jsObj, "local_obj");

		Bundle data = getIntent().getExtras();
		if (data != null && data.size() > 0) {
			if (data.containsKey("url")) {
				String url = data.getString("url");

				HashMap<String, String> maps = new HashMap<String, String>();
				maps.put("UserId", LoginUtil.getUserId());
				maps.put("LoginToken", LoginUtil.getLoginToken());

				mLoadUrl = UtilityBase.connectParamsUrl(url, maps);
				
				Utils.initWebViewSettings(mWebView,false);

				//test
				//mLoadUrl = "http://app.xiaomi.com/details?id=com.lepu.pasm&from=singlemessage&isappinstalled=0";
			}

			if (data.containsKey("title")) {
				mTopbarTitle = data.getString("title");
			}

			if (data.containsKey("load_data")) {
				mLoadData = data.getString("load_data");
				
				Utils.initWebViewSettings(mWebView,true);
			}

			if (data.containsKey("need_share")) {
				mNeedShare = data.getBoolean("need_share");
			}
			
			if (data.containsKey("from_type")) {
				mFromType = data.getInt("from_type");
			}

			if (data.containsKey("Cover")) {
				mCover = data.getString("Cover");
			}

			if (data.containsKey("Description")) {
				mDescription = data.getString("Description");
			}
		}

		if (mTopbarTitle.length() > 0) {
			mTopbar.setTopbarTitle(mTopbarTitle);
			mShareTitle = mTopbarTitle;
		}
		
		// 是否需要分享
		mShareImageView = (ImageView) findViewById(R.id.shareImageView);
		if (mNeedShare) {
			mShareImageView.setVisibility(View.VISIBLE);
		} else {
			mShareImageView.setVisibility(View.GONE);
		}

		// other
		if (!TextUtils.isEmpty(mLoadData)) {
			showWebViewLoadData();
		} else {
			showWebViewUrl();
		}
	}

	private void closePage() {
		if (mWebView.canGoBack()) {
			mWebView.goBack();

			//mTopbar.setTopbarTitle(mTopbarTitle);
			return;
		}

		finish(true);
	}

	public void showWebViewUrl() {

		if (!StringUtilBase.stringIsEmpty(mLoadUrl)) {
			mWebView.loadUrl(mLoadUrl);
		}
	}

	public void showWebViewLoadData() {

		if (!StringUtilBase.stringIsEmpty(mLoadData)) {
			mWebView.loadData(mLoadData, "text/html; charset=UTF-8", null);
		}
	}

	// ======================================================
	class MyWebChromeClient extends WebChromeClient {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			// LogUtilBase.LogD(null, "onProgressChanged===>>" + newProgress);
			mProgressBar.setMax(100);
			if (newProgress < 100) {
				if (mProgressBar.getVisibility() == View.GONE) {
					mProgressBar.setVisibility(View.VISIBLE);
				}
				mProgressBar.setProgress(newProgress);
			} else {
				mProgressBar.setProgress(100);

				Animation animation = AnimationUtils.loadAnimation(AppBroswerActivity.this,
						R.anim.lib_broswer_progress);
				// 运行动画
				mProgressBar.startAnimation(animation);
				// 将 spinner 的可见性设置为不可见状态
				mProgressBar.setVisibility(View.GONE);
			}
		}

		//====================
		// private View xprogressvideo;
		// 播放网络视频时全屏会被调用的方法
		@Override
		public void onShowCustomView(View view, CustomViewCallback callback) {
			//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			mWebView.setVisibility(View.INVISIBLE);
			// 如果一个视图已经存在，那么立刻终止并新建一个
			if (mCustomVideoView != null) {
				callback.onCustomViewHidden();
				return;
			}
			mVideoFullView.addView(view);
			mCustomVideoView = view;
			mCustomViewCallback = callback;
			mVideoFullView.setVisibility(View.VISIBLE);
		}

		// 视频播放退出全屏会被调用的
		@Override
		public void onHideCustomView() {
			if (mCustomVideoView == null)// 不是全屏播放状态
				return;

			//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			mCustomVideoView.setVisibility(View.GONE);
			mVideoFullView.removeView(mCustomVideoView);
			mCustomVideoView = null;
			mVideoFullView.setVisibility(View.GONE);
			mCustomViewCallback.onCustomViewHidden();
			mWebView.setVisibility(View.VISIBLE);
		}

		// 视频加载时进程loading
		@Override
		public View getVideoLoadingProgressView() {
//            if (xprogressvideo == null) {
//                LayoutInflater inflater = LayoutInflater
//                        .from(MainActivity.this);
//                xprogressvideo = inflater.inflate(
//                        R.layout.video_loading_progress, null);
//            }
//            return xprogressvideo;
			return null;
		}

	}


	public void onPageStarted(String url) {
		LogUtilBase.LogD(null, "onPageStarted===>>" + url);
	}

	@Override
	public boolean shouldOverrideUrlLoading(WebView webView, String url) {
		LogUtilBase.LogD(null, "shouldOverrideUrlLoading == >>"+url);

		if (!TextUtils.isEmpty(url)) {

			if (url.startsWith("tel:")) {
				Utils.callPhone(AppBroswerActivity.this, url.substring(4, url.length()));
			} else if (url.startsWith("http")) {
				webView.loadUrl(url);
			} else {
				try {
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
				} catch (Exception e) {
					webView.loadUrl(url);
				}
			}
		}
		return true;
	}

	public void onPageFinished(String url) {
		LogUtilBase.LogD(null, "onPageFinished===>>" + url);
	}

	@SuppressWarnings("deprecation")
	private void showHideShare(boolean isShow) {
		if (isShow) {
			mShareImageView.setAlpha(255);
		} else {
			mShareImageView.setAlpha(100);
		}
	}

	/***
	 * 监听webview 滚动
	 */
	@SuppressWarnings("deprecation")
	@Override
	public void onScrollChanged(int l, int t, int oldl, int oldt) {
		LogUtilBase.LogD(null, "AppBroswerActivty webview onScrollChanged");

		if (!mNeedShare) {
			return;
		}

		float webContent = mWebView.getContentHeight() * mWebView.getScale();// webview的高度
		float webNow = mWebView.getHeight() + mWebView.getScrollY();// 当前webview的高度

		LogUtilBase.LogD(null, "webContent的高度" + webContent);
		LogUtilBase.LogD(null, "webNow的高度" + webNow);

		//底端算的有些偏差，不到10px
		if (((mWebView.getContentHeight() * mWebView.getScale())
				- (mWebView.getHeight() + mWebView.getScrollY())) < 10) {
			LogUtilBase.LogD(null, "webview到底端了");
			// 已经处于底端
			showHideShare(true);
		} else if (mWebView.getScrollY() == 0) {
			LogUtilBase.LogD(null, "webview到顶端了");
			// 已经处于顶端
			showHideShare(true);
		} else {
			showHideShare(false);
		}
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_ARTICLE_SHARE)) {
			LogUtilBase.LogD(null, "share article success");
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_ARTICLE_SHARE)) {
			LogUtilBase.LogD(null, "share article fail");
		}
	}

	private void clickShare() {

		showHideShare(true);

		String imgPath = SdLocal.getAppIconPath(getApplicationContext());
		if(!TextUtils.isEmpty(mCover))
		{
			imgPath = mCover;
		}

		// 调用官方sdk分享，可以各种形式
		ShareLib.Share(this, mShareTitle, mDescription, imgPath, mLoadUrl, false,
				new CallBack() {
					@Override
					public void callBackSuccess(Object obj) {
						super.callBackSuccess(obj);

						MyNetUtil.getInstance().requestShare(
								AppBroswerActivity.this, 2, "-1");
					}
				});
	}

	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.shareImageView:

			clickShare();
			break;

		default:
			break;
		}
	}

	// ================test==========================
	@Override
	@SuppressLint("SetJavaScriptEnabled")
	@JavascriptInterface
	public void getTitle(final String title) {
		LogUtilBase.LogD(null, String.format("webview title====>>%s", title));

		mShareTitle = title;
		if (TextUtils.isEmpty(mTopbarTitle)) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mTopbar.setTopbarTitle(title);
				}
			});

		}
	}

	@Override
	@SuppressLint("SetJavaScriptEnabled")
	@JavascriptInterface
	public void getVideoSrc(String videoSrc) {
		LogUtilBase.LogD(null,
				String.format("webview videoSrc===>>%s", videoSrc));
	}

	@Override
	@SuppressLint("SetJavaScriptEnabled")
	@JavascriptInterface
	public void getHtmlLength(int HtmlLength) {
		LogUtilBase.LogD(null,
				String.format("webview HtmlLength===>>%d", HtmlLength));
	}

	@Override
	@SuppressLint("SetJavaScriptEnabled")
	@JavascriptInterface
	public void getReferrer(String Referrer) {
		LogUtilBase.LogD(null,
				String.format("webview Referrer===>>%s", Referrer));
	}
	//=============================================
	@Override
	@SuppressLint("SetJavaScriptEnabled")
	@JavascriptInterface
	public void getArticleID(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	@SuppressLint("SetJavaScriptEnabled")
	@JavascriptInterface
	public void getCover(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	@SuppressLint("SetJavaScriptEnabled")
	@JavascriptInterface
	public void getDescription(String arg0) {
		// TODO Auto-generated method stub
		
	}

}
